package com.ruoyi.client.service.impl;


import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.ruoyi.client.mapper.ClientUserTMapper;
import com.ruoyi.client.service.IUserTService;
import com.ruoyi.common.core.domain.entity.UserT;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-17
 */
@Service
public class ClientUserTServiceImpl implements IUserTService
{
    @Autowired
    private ClientUserTMapper userTMapper;

    @Override
    public String getAccessToken() throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey("dingyheus4qvl9wqmdv8");
        request.setAppsecret("Fq9_T-ju8-vujQPPIXgM4CrbGDrE0NGA8bxgudIsFFOs4n-G8fqCwwXtLP7nqTQm");
        request.setHttpMethod("GET");
        OapiGettokenResponse response = client.execute(request);
        return response.getAccessToken();
    }

    @Override
    public UserT getUser(String authCode, String accessToken) throws ApiException {
        //2、获取用户id
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
        OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
        req.setCode(authCode);
        OapiV2UserGetuserinfoResponse rsp = client.execute(req, accessToken);
        UserT userT = new UserT();
        userT.setId(rsp.getResult().getUserid());
        userT.setNick(rsp.getResult().getName());
        return userT;
    }

    @Override
    public String initUser(String authCode) throws ApiException {
        //1、获取accessToken
        String accessToken = getAccessToken();
        //2、获取用户信息
        UserT user = getUser(authCode, accessToken);
        //3、看用户是否已被初始化
        UserT user1 = userTMapper.getUser(user.getId());
        if(user1!=null){
            return user1.getId();
        }else {
            user.setCredit(0L);
            userTMapper.insertUser(user);
            return user.getId();
        }

    }

    @Override
    public UserT getUserById(String userId) {
        return userTMapper.getUser(userId);
    }


}
